package com.badger.generator;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.badger.generator.entity.BuildResult;
import com.badger.generator.entity.GeneratorAttr;

public class MakeIntegerFace {
	 
	 private static Map<String,Object> defaultValue=null;
	
	 public static final String TABS = "    ";
    /**
     * 换行符  
     * java 与平台无关 System.getProperty("line.separator"); 
     */
	 public static final String LINE_SEPARATOR =  System.getProperty("line.separator");
	 //public static final String LINE_SEPARATOR = "\n";
	 
	 private static String  baseResponse="{"+LINE_SEPARATOR
		 		+ "\"code\":0,"+"      //code为0标识成功，其他为失败提示msg"+LINE_SEPARATOR
		 		+ "\"msg\":\"XXXX\","+LINE_SEPARATOR
		 		+ "\"data\":[{"+LINE_SEPARATOR
		 		+"result" +LINE_SEPARATOR
		 		+"    "+ "}]"+LINE_SEPARATOR
		 		+ "}";

	 private static String regex = "(\\/\\*\\*(.*|\\n.*){0,4}\\n.*private.*;)|(\\n.*private.*;)";
	 //String regex = "(\\/\\*\\*(.*|\\r\\n.*){0,4}\\r\\n.*private.*;)|(\\r\\n.*private.*;)";
	
	  public static void main(String[] args) throws IOException {
		  List<InterfaceParam> ifps=new ArrayList<>();
		  StringBuilder sb=new StringBuilder();
		  InterfaceParam infa=new InterfaceParam();
		  infa.setInterfaceName("商品库列表查询");
		  infa.setRequestUrl("https://fanyi.baidu.com");
		  infa.setParamter(BuildResult.class);
		  infa.setResult(GeneratorAttr.class);
		  ifps.add(infa);
		  
		  for(InterfaceParam ifp:ifps) {
			  String className,src,content;byte[] bytes;
			//生成参数
			  if(infa.getParamter()!=null) {
				  className=infa.getParamter().toString().substring(infa.getParamter().toString().lastIndexOf(".")+1, infa.getParamter().toString().length());
				  src=getPackagePath(infa.getParamter())+className+".java";
				  src=src.replace("/target/classes", "/src/main/java");
				  bytes = Files.readAllBytes(Paths.get(src));
		    	  content = new String(bytes, StandardCharsets.UTF_8);
		    	  
		    	  String paramContent= parse2(content);
		    	  infa.setParamContent(paramContent);
				  
			  }
			  
	    	  //生成返回值
			  if(infa.getResult() != null) {
				  className=infa.getResult().toString().substring(infa.getResult().toString().lastIndexOf(".")+1, infa.getResult().toString().length());
				  src=getPackagePath(infa.getResult())+className+".java";
				  src=src.replace("/target/classes", "/src/main/java");
				  bytes = Files.readAllBytes(Paths.get(src));
		    	  content = new String(bytes, StandardCharsets.UTF_8);
		    	  
		    	  String resultContent= parse2(content);
		    	  resultContent=baseResponse.replace("result", resultContent);
		    	  infa.setResultContent(resultContent);
			  }else {
		    	  infa.setResultContent(baseResponse.replace("result", ""));
			  }
	    	  
	    	  sb.append(infa.getContent());
	    	  System.out.println(infa.getContent());
			  
		  }
    	  
		  writeInterFace(sb.toString(),"D:\\接口文档","接口文档.txt");
		  
		  openFile("D:\\接口文档");
	    }
	  
	  
	  public static String  parse2(String str) {
		    StringBuilder sb = new StringBuilder();
			//1、将正则规则进行对象封装
			Pattern pat = Pattern.compile(regex);
			//2、通过正则对象获取匹配器对象
			Matcher mat = pat.matcher(str);
			//3、查找
			//System.out.println("查找");
			while (mat.find()) {
				//4、获取当前子序列
				//System.out.println(mat.group());
				readLine(mat.group(), sb);
			}
			System.out.println("###################################");
			//System.out.println(JSON.toJSONString(result));
			return sb.toString();
		}
	  
	  public static void readLine(String str,StringBuilder sb ) {
		    String str1=str.replaceAll("\\/\\*\\*", "");//去掉/**
		   
			String value=str1.split( "\\*\\/")[0];
			value=value.replaceAll("\\*", "");
			value=value.replaceAll("\\n", "");
			value=value.replaceAll(" ", "");
			//value=value.replaceAll("\\r", "");
			
			String strayy []=str1.split("\\n");
			String key=strayy [strayy.length-1].trim();
			key=key.replace(";", "");
			String keyarr[]=key.split( " ");
			if(keyarr.length !=3) {
				return ;
			}
			key=keyarr[2];
			
			String cloumType=keyarr[1];
			
			defaultValue.get(cloumType);
			
			//result.put(key, value);
			sb.append(TABS).append("\""+key+"\""+":"+defaultValue.get(cloumType)+", //"+value).append(LINE_SEPARATOR);
			//System.out.println("\""+key+"\""+":\""+"\", //"+value);
			//System.out.println("\""+key+"\""+":"+defaultValue.get(cloumType)+", //"+value);
		}
	  
	  public static String getPackagePath(Class<?> class1)  
	    {  
		//获取包路径
	        String thisPackagePath=class1.getResource("").toString();  
	        int m=thisPackagePath.indexOf("/");//去掉前面的file:  
	        thisPackagePath=thisPackagePath.substring(m+1);  
	        return thisPackagePath;//返回当前包返回的路径。  
	    }
	  
	  /**
	     * 把对应的文件，写入文件夹内
	     * @param path
	     * @return
	     */
	    public static void writeInterFace(String fileContent,String path,String fileName ) {
	    	 File beanFile = new File(getFilePath(path), fileName);
	            try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(beanFile)));) {
	                bw.write(fileContent);
	                bw.flush();
	            	bw.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            } 
	        return ;
	    }
	    
	    public static String getFilePath(String savePath) {
	        File folder = new File(savePath);
	        if (!folder.exists()) {
	            folder.mkdirs();
	        }
	        return folder.getPath();
	    }
	    
	    static {
	    	defaultValue = new HashMap<>();
	    	defaultValue.put("String", "\"XXX\"");
	    	defaultValue.put("Integer", 0);
	    	defaultValue.put("int", 0);
	    	defaultValue.put("Double", 0.02);
	    	defaultValue.put("double", 0.02);
	    	defaultValue.put("float", 0.02);
	    	defaultValue.put("Float", 0.02);
	    	defaultValue.put("Long", 1.1111);
	        defaultValue.put("long", 1.1111);
	        defaultValue.put("BigDecimal", 0.02);
	        defaultValue.put("LocalDateTime",LocalDateTime.now().toString().replace("T", " "));
	        defaultValue.put("boolean",true);
	        


	    }
	    
	    public static void openFile(final String path) {
	        try {
	            String osName = System.getProperty("os.name");
	            if (osName != null) {
	            	if (osName.contains("Windows")) {
	                    Runtime.getRuntime().exec("cmd /c start " + path);
	                }
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	       
	    }
	   

}
